﻿#region

using System.Windows;
using System.Windows.Media;

#endregion

namespace Radovici.SharedLibrary
{
    public static class VisualTreeHelperExtensions
    {
        public static bool IsChildOf(this UIElement child, UIElement parent, int distance)
        {
            if (distance != 0)
            {
                var element = VisualTreeHelper.GetParent(child) as UIElement;
                if (element != null)
                {
                    if (element == parent)
                    {
                        return true;
                    }
                    return IsChildOf(element, parent, distance - 1);
                }
            }
            return false;
        }

        public static T FindParent<T>(this UIElement element) where T : UIElement
        {
            if (element == null)
            {
                return null; //throw new ArgumentNullException("FrameworkElement can not be null.");
            }
            if (typeof (T).IsAssignableFrom(element.GetType()))
            {
                return element as T;
            }
            return FindParent<T>(VisualTreeHelper.GetParent(element) as UIElement);
        }
    }
}